<template>
  <div class="common_block_div">
    <div class="">
      <div class=" ">

      <div class="common_button flex_ac">
        <div class="right_button margin_a flex">
          <a href="javascript:;" class="color_blue" @click="handleUpdate" >新增</a>
          <!-- <a href="javascript:;" class="color_red" @click="handleDelete" >删除</a> -->
        </div>
      </div>


      <el-table v-loading="loading" :data="list" border @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" :selectable="selectable_fun" /> -->
        <el-table-column label="角色ID" align="center" prop="id"  />
        <el-table-column label="角色名称" align="center" prop="role_name"  />
        <!-- <el-table-column label="权限字符" align="center" prop="id"  />
        <el-table-column label="显示顺序" align="center" prop="id"  /> -->
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" @change="sw_change($event,scope.row)" :active-value="1" :inactive-value="0" :disabled="scope.row.id==1  || !have_auth('/system/role/edit')"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="create_time"  />
        <el-table-column label="更新时间" align="center" prop="update_time"  />
        <el-table-column label="由谁创建" align="center" prop="create_by"  />
        <el-table-column label="备注" align="center" prop="role_desc"  />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180px" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleUpdate(scope.row)" v-if="scope.row.id!=1 && have_auth('/system/role/edit')">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" v-if="scope.row.id!=1 && have_auth('/system/role/del')">删除</el-button>
            <el-button type="text" size="small" @click="handleDataScope(scope.row)"  v-if="scope.row.id!=1 && have_auth('/system/role/auth')">菜单权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.limit"
        @pagination="getList"
      />
    </div>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" title="新增/编辑角色" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <FormItem label="角色名称" class="" :span="24" type="input" :form="form" prop="role_name" clearable />
          <FormItem label="备注" class="" :span="24" type="textarea" :form="form" prop="role_desc" clearable />
          <el-col :span="24">
          	<el-form-item label="状态" prop="status">
              <el-switch v-model="form.status" :active-value="1" :inactive-value="0" :disabled="form.id==1"></el-switch>
          	</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open=false;">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')" :loading="is_ajax">{{is_ajax?'保存中···':'确定'}}</el-button>
      </div>
    </el-dialog>


    <el-dialog v-dialogDrag class="role_sele_tree"  :visible.sync="openDataScope" append-to-body title="设置权限" width="800px" center :close-on-click-modal="false">
        <!-- <el-select v-model="newlist" multiple placeholder="请选择" style="width:100%;margin-bottom:10px"
            @remove-tag="splicenews">
        </el-select> -->
        <div class="pad_b10"><el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox></div>
        <div style=" border: 1px solid #eee; border-radius: 0px;" class="org_sele_tree">
          <el-scrollbar hidex style="position:relative;height: 500px;">

              <el-tree
                :default-expand-all="true"
                :data="menuOptions"
                show-checkbox
                check-on-click-node
                ref="menu"
                node-key="id"
                empty-text="加载中，请稍后"
                :props="defaultProps"
              >
                <template  #default="{ node, data }">
                    <span class="custom-tree-node" >
                        <span :class="'js_node_'+data.menu_type" :data-id="data.id">{{ data.menu_name }}</span>
                    </span>
                </template>
              </el-tree>
          </el-scrollbar>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelDataScope">取消</el-button>
          <el-button type="primary" :loading="is_ajax" @click="submitDataScope">提交</el-button>
        </div>
    </el-dialog>

  </div>
</template>

<script>
import $ from "jquery";
export default {
  name: 'needCache',
  data () {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      activeName:'1',  // 1进行中 2 已结束
      loading: true,
      total: 0,
      // 定时任务表格数据
      list: [],
      // 查询参数
      queryParams: {
        page: 1,
        limit: 16
      },
      openOptions: [{id:'1',title:'选项1'},{id:'2',title:'选项2'}],
      open:false,
      // 表单参数
      form: {status:1,role_name:'',role_desc:''},
      // 表单校验
      rules: {
        role_name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ]
      },
      is_ajax:false,

      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      menuOptions:[],
      op_id:'',
      defaultProps: {
        children: "children",
        label: "menu_name"
      },
    }
  },
  activated() {
    this.getList();
  },
  methods:{

    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },

    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset2();
    },
    // 权限表单重置
    reset2() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false;
      this.menuNodeAll = false;
      this.deptExpand = true;
      this.deptNodeAll = false;
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.op_id=row.id;
      const _this=this;
      _this.openDataScope=true;

      _this.axios.get("/manage/admin.RolePermission/role_permissions", {params:{roleId:row.id}}).then((res) => {
          if (res) {
            _this.menuOptions = res.message.permission_tree;
              let check_ids=res.message.menu_id || [];
              _this.$nextTick(() => {
                for(let i=0;i<check_ids.length;i++){
                  _this.$refs.menu.setChecked(check_ids[i],true)
                }
                _this.$nextTick(() => {
                  $(".js_node_3")
                  .parent(".custom-tree-node")
                  .parent(".el-tree-node__content")
                  .parent(".el-tree-node")
                  .parent(".el-tree-node__children")
                  .addClass("pingpu_display_wrap");
                });
              });
          } else {
              // _this.$message.error(res.message);
          }
      }).catch((err) => {
          console.log(err);
      });
    },

    /** 提交按钮（数据权限） */
    submitDataScope: function() {
      if(this.is_ajax){return false;}
      let data={
        roleId:this.op_id,
        permissions:this.getMenuAllCheckedKeys()
      }
      this.is_ajax=true;
      this.axios.post("/manage/admin.RolePermission/save_role_permissions", data).then((res) => {
          if (res.status == 200) {
              this.$message.success('设置成功');
              this.reset2();
              this.openDataScope=false;
              this.getList();
          } else {
              // this.$message.error(res.message);
          }
          this.is_ajax=false;
      }).catch((err) => {
          console.log(err);
          this.is_ajax=false;
      });
    },
    sw_change(e,row){
      const _this=this;
      row.status=e;
      let _data={...row};
      let url="/manage/admin.Role/save";
      _this.axios.post(url, _data).then(function(data) {
        if(data){
          _this.tip_show('操作成功','success');
          // _this.getList()
        }
        _this.is_ajax=false;
      }).catch(function(error) {
        _this.is_ajax=false
        console.log(error);
      })

    },
    selectable_fun(row){
        if(row.id==1 || row.id==2){
            return false;
        }
        return true
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleDetail(row){
      this.$store.commit('set_cur_pro',row)
      this.$router.push({ //核心语句
        path: '/project/sampling?id='+row.id,
      })
    },
    // 表单重置
    reset() {
      this.form = {status:1,role_name:'',role_desc:''};
      if(this.$refs['form']){
        this.$refs['form'].clearValidate();
      }
    },
    /** 提交按钮 */
    submitForm: function(form) {
      const _this=this;
      this.$refs[form].validate(valid => {
        if (valid) {
          this.is_ajax=true;
          let _data={..._this[form]};
          let url="/manage/admin.Role/save";
          _this.axios.post(url, _data).then(function(data) {
            if(data){
              _this.tip_show('操作成功','success');
              _this.open=false;
              _this.getList()
            }
            _this.is_ajax=false;
          }).catch(function(error) {
            _this.is_ajax=false
            console.log(error);
          })
        }
      });
    },
    /** 查询定时任务列表 */
    getList() {
      const _this=this;
      this.loading = true;
      _this.axios.get("/manage/admin.Role/index", {params:this.queryParams}).then(function(res) {
        if(res){
          _this.list = res.message.data;
          _this.total = res.message.total;
          _this.loading = false;
          // _this.openOptions=_this.obj2arr(res.message.search.status)
        }
      }).catch(function(error) {
        console.log(error);
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams={
        page: 1,
        limit: 16
      }
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row){
      this.reset()
      this.form=row.id?{...row}:{status:1,role_name:'',role_desc:''};
      this.open=true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const _this=this;
      const ids = row.id;
      if(ids.length==0){
        _this.$message.error('请选择要操作的数据');
        return false;}
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          _this.axios.post("/manage/admin.Role/delete", {id:ids}).then((res) => {
              if (res) {
                  _this.getList();
                  _this.$message.success('操作成功');
              }
          }).catch((err) => {
              console.log(err);
          });
        })
    },

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .title{line-height: 44px; font-size: 20px;}
</style>
